<template>
  <el-form
    ref="deptForm"
    label-width="120px"
    :model="form"
    :rules="rules"
  >
    <el-form-item
      label="部门名称"
      prop="name"
    >
      <el-input
        v-model="form.name"
        style="width:80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item
      label="部门编码"
      prop="code"
    >
      <el-input
        v-model="form.code"
        style="width:80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item
      label="部门负责人"
      prop="manager"
    >
      <el-select
        v-model="form.manager"
        style="width:80%"
        placeholder="请选择"
      >
        <el-option
          v-for="item in employeesList"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      label="部门介绍"
      prop="introduce"
    >
      <el-input
        v-model="form.introduce"
        style="width:80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        @click="hSubmit"
      >
        确定
      </el-button>
      <el-button
        size="small"
        @click="emit('close')"
      >
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments ,getDepartmentsById,updateDepartments } from '@/api/departments'
//表单验证数据
const deptForm = ref<FormInstance>()
let form = reactive({
  name: '', // 部门名称
  code: '', // 部门编码
  manager: '', // 部门管理者
  introduce: '', // 部门介绍
})
//验证code的编码,唯一值
const validateCode = (rule: any, value: string, callback:any) => {
  let exsitCodeList=props.originList.map(item=>item.code)
  if(props.isEdit){
    // 把当前正在编辑的部门编号（this.id）排除在外
    exsitCodeList=props.originList.filter(item=> item.id!==props.id).map(item=>item.code)
  }
  console.log('exsitCodeList',exsitCodeList)
  exsitCodeList.includes(value)?callback(new Error(`${ value }已经存在,请重新输入`)) : callback()
}
//验证同级部门的名字不能一致
const validateName=(rule:any ,value:string,callback:any) => {
  console.log('props.id',props.id)
  let exsitNameList=props.originList.filter(item=>item.pid===props.id).map(item=>item.name)
  if (props.isEdit) {
    const current =props.originList.find(item=>item.id===props.id)
    const pid =current?.pid
    exsitNameList=props.originList.filter(item=>item.pid===pid&& item.id!==props.id).map(item=>item.name)
  }
  console.log('exsitNameList',exsitNameList)
  exsitNameList.includes(value)?callback(new Error(`${ value }已经存在,请重新输入`)) : callback()
}
//验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '部门名必填', trigger: 'blur' },
    { min: 1, max: 15, message: '用户名的长度为1-15位', trigger: 'blur' },
    { validator:validateName, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '部门编码必填', trigger: 'blur' },
    { min: 1, max: 15, message: '部门编码的长度为1-15位', trigger: 'blur' },
    { validator:validateCode, trigger: 'blur' },
  ],
  manager: [
    { required: true, message: '部门负责人必填', trigger: 'blur' },
    { min: 1, max: 15, message: '部门负责人的长度为1-15位', trigger: 'blur' },
  ],
  introduce: [
    { required: true, message: '部门介绍必填', trigger: 'blur' },
    { min: 1, max: 50, message: '部门负责人的长度为1-50位', trigger: 'blur' },
  ],

})
//兜底验证
const hSubmit =() => {
  //增加子部门
  props.isEdit ? loadUpdateDepartments():loadAddDepartments()
}
//重置表单
const resetForm=() => deptForm.value?.resetFields()
//获取简单员工列表
type EmployeesList={
    id:string
    username:string
}
//获取简单员工列表
const employeesList=ref<Array<EmployeesList>>()
const loadEmployeeSimple=async () => {
  try {
    const res = await getEmployeeSimple()
    console.log('获取简单员工列表',res)
    employeesList.value=res.data
    console.log('employeesList.value', employeesList.value)
  } catch (error) {
    console.log(error)
  }
}
//进入页面调用
loadEmployeeSimple()
//接收参数
const props=defineProps<{
    id:string,
    isEdit:boolean
    showDialog:boolean
    originList:Origin[]
}>()
//注册自定义事件
const emit =defineEmits(['success','close'])
//取消时关闭
// const onClose=() => {
//   emit('close')
// }
//console.log('props.id',props.id)
//新增子部门
const loadAddDepartments =async() => {
  try {
    const data ={ ...form,pid:props.id }
    const res = await addDepartments(data)
    console.log('增加子部门',res)
    emit('success')
  } catch (error) {
    console.log(error)
  }
}
//根据id获取详情
const loadDepartmentsById =async() => {
  try {
    const res = await getDepartmentsById(props.id)
    console.log('根据id获取详情',res)
    //覆盖form表单
    form = Object.assign(form,res.data)
    //console.log('form',JSON.stringify(form))
  } catch (error) {
    console.log(error)
  }
}
//进入页面调用
loadDepartmentsById()
//编辑部门
const loadUpdateDepartments =async() => {
  try {
    const res = await updateDepartments(form as UpdateDepartments)
    console.log('编辑部门',res)
    //调用自定义事件
    emit('success')
  } catch (error) {
    console.log(error)
  }
}
//将方法暴露
defineExpose({
  loadDepartmentsById,
  resetForm,
})
</script>